import {
  reqCode
} from '@/api/common'
import {
  reqLogin
} from '@/api/index'
import userStore from '@/store/userStore'
import {
  ComponentWithStore
} from 'mobx-miniprogram-bindings'
import {
  reqUserInfo
} from '@/api/user'
import {
  setStorage
} from '@/utils/storage'
import verifier from '@/utils/verifier'
ComponentWithStore({

  storeBindings: {
    store: userStore,
    fields: ["token", "userInfo"],
    actions: ["setToken", "setUserInfo"]
  },


  data: {
    errorPhone: "",
    phone: "",
    code: "",
    time: 1000 * 60,
    showSendCode: true
  },

  methods: {

    verifyPhone() {
      if (!this.data.phone) {
        this.setData({
          errorPhone: "手机号不能为空"
        })
        return false;
      }
      if (!verifier.verifyPhone(this.data.phone)) {
        this.setData({
          errorPhone: "手机号格式错误"
        })
        return false;
      }
      this.setData({
        errorPhone: ""
      })
      return true;
    },

    async sendCode() {
      if (!this.verifyPhone()) {
        return
      }
      await reqCode(this.data.phone)
      this.setData({
        showSendCode: false
      })
    },
    finshCount() {
      this.setData({
        showSendCode: true
      })
    },
    async login() {
      if (!this.verifyPhone()) {
        return
      }
      const res = await reqLogin({
        phone: this.data.phone,
        code: this.data.code
      })
      // 本地化token
      this.setToken(res.data)
      setStorage('user.token', res.data)
      const result = await reqUserInfo()
      // 本地化用户信息
      this.setUserInfo(result.data)
      setStorage('userInfo', result.data)
      wx.switchTab({
        url: '/pages/index/index'
      })
    }
  }
})